package com.banfeiguanli.springboot.service;

import com.banfeiguanli.springboot.common.Result;
import com.banfeiguanli.springboot.entity.Notice;
import com.banfeiguanli.springboot.entity.User;
import com.banfeiguanli.springboot.entity.dto.NoticeDTO;
import com.banfeiguanli.springboot.mapper.NoticeMapper;
import com.banfeiguanli.springboot.mapper.UserMapper;
import com.banfeiguanli.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service//注入springboot容器
public class NoticeService {

    @Autowired//注入类
    private NoticeMapper noticeMapper;
    @Autowired//注入类
    private UserMapper userMapper;

    public Result getAllNotice() {
        Map<String, Object> data = new HashMap<>();
        //查询公告信息
        List<Notice> noticeList = noticeMapper.getAllNotice();
        data.put("allNotice", noticeList);
        return Result.success(data);
    }

    private boolean userExist(int userID) {
        List<User> userList = userMapper.getUserInfo(userID);
        return !userList.isEmpty();
    }

    //查询全体公告(后台管理)
    public Result getNoticeInfo(String token, Integer pageNumber, Integer pageSize, String searchTitle) {
        Map<String, Object> data = new HashMap<>();
        //查询
        pageNumber = (pageNumber - 1) * pageSize;
        List<Notice> allNotice = noticeMapper.getNoticeInfo(pageNumber, pageSize, searchTitle);
        data.put("allNotice", allNotice);
        //统计总数
        Integer allNoticeTotal = noticeMapper.countAllNoticeTotal(searchTitle);
        data.put("allNoticeTotal", allNoticeTotal);
        return Result.success(data);
    }

    //删除公告
    public Result deleteNotice(String token, Integer noticeID) {
        //删除数据
        Integer deleteRow = noticeMapper.deleteNotice(noticeID);
        if (deleteRow != 1) {
            return Result.error("删除失败！");
        }
        return Result.success("删除成功！", null);
    }

    //发布全体公告
    public Result addNotice(NoticeDTO noticeDTO) {
        //提取adminID
        Integer adminID = TokenUtils.getIdByToken(noticeDTO.getToken());
        noticeDTO.setAdminID(adminID);
        //插入数据
        Integer insertRow = noticeMapper.addNotice(noticeDTO);
        if (insertRow != 1) {
            return Result.error("发布失败！");
        }
        return Result.success("发布成功！", null);
    }
}
